var express = require("express");
var path = require("path");
var fs = require("fs");
const { v4: uuidV4 } = require("uuid");
var app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

const A_DAY = 24 * 60 * 60 * 1000;
const week = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];

// 允许跨域访问  使用的是cors解决跨域问题，当我们再本地直接请求该接口的时候，可以直接请求
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", " 3.2.1");
  // res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

app.post("/getLocations", (req, res, next) => {
  res.send({
    from: "北京",
    to: "三亚",
  });
});

app.post("/getRecent5DayData", (req, res, next) => {
  console.log("getRecent5DayData", req.body);
  const reqDate = req.body.date;
  const date = new Date(reqDate);

  const today = new Date(getDay(new Date()));
  console.log("today", today, date);
  const diff = (date.valueOf() - today.valueOf()) / A_DAY;
  console.log(diff);
  if (diff < 0)
    res.status(400).send({
      msg: "error",
    });
  //diff >=2 从date -2 这天算起   否则 从today这天算起

  const startDate = diff >= 2 ? new Date(date - 2 * A_DAY) : today;
  console.log(diff >= 2, startDate);

  let idx = -2;
  const resData = Array(9)
    .fill(0)
    .map((_, index) => {
      const date = new Date(startDate.valueOf() + idx * A_DAY);
      idx++;
      console.log("-", idx, date);
      if (date.valueOf() < today.valueOf()) return null;
      return {
        date: getDay(date),
        week: date.valueOf() === today.valueOf() ? "今天" : week[date.getDay()],
        price: Math.ceil(Math.random() * 1000 + 1),
        isTargetDate: reqDate === getDay(date),
        start: date.valueOf() === startDate.valueOf(),
      };
    })
    .filter((val) => val !== null);

  res.send({
    data: JSON.stringify(resData),
  });
});

app.post("/getList", (req, res) => {
  let t1 = "06:00";
  const resData = Array(Math.ceil(Math.random() * 10 + 5))
    .fill(0)
    .map(() => {
      t1 = addAHour(t1);
      const [hours, minutes] = t1.split(":").map(Number);
      const p = Math.ceil(Math.random() * 1000) + 1;
      return {
        id: uuidV4(),
        startTime: t1,
        endTime: addAHour(t1),
        departureAirport: "首都T3",
        landingAirport: "虹桥T2",
        flightName: "东航MU5138空客A330（宽）",
        price: "￥" + p,
        realPrice: p,
        priceDesc: "经济舱7.4折",
        tips: Math.random() > 0.5 ? "持续涨价中" : undefined,
        seconds: hours * 3600 + minutes * 60,
      };
    });
  resData.sort(() => Math.random() - 0.5);
  console.log(resData);
  res.send(JSON.stringify(resData));
});
app.listen(8080, () => {
  console.log("8080");
});

const getDay = (date) =>
  `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;

const generateRandomTime = () => {
  const hours = Math.floor(Math.random() * 20);
  const minutes = Math.floor(Math.random() * 60);

  const formattedHours = hours.toString().padStart(2, "0");
  const formattedMinutes = minutes.toString().padStart(2, "0");

  return `${formattedHours}:${formattedMinutes}`;
};

const addAHour = (time) => {
  const t = time.split(":");
  const h = (Number(t[0]) + 1).toString().padStart(2, "0");
  const m = Math.floor(Math.random() * 60)
    .toString()
    .padStart(2, "0");
  return `${h}:${m}`;
};
